import vnode from "./vnode";
import createElement from "./createElemnt";

export default function patch(oldNode, newNode) {
    if (oldNode.sel === '' || oldNode.sel === undefined) {
        oldNode = vnode(oldNode.tagName.toLowerCase(), {}, [], undefined, oldNode)
    }
    if(oldNode.key === newNode.key && oldNode.sel === newNode.sel) {
        console.log("same key")
        if(oldNode === newNode) return
        // 判断是否有text
        if (newNode.text !== undefined && (newNode.children === undefined || newNode.children.length === 0)) {
            console.log("新node有text属性")
            console.log(oldNode.elm)
            
            // 有text
            oldNode.elm.innerText = newNode.text
        } else {
            // 没有text,那就是有children
            if (oldNode.children !== undefined && oldNode.children.length !== 0) {
                // 老的有children
            } else {
                // 老的节点没有children
                console.log("老的有children")
                oldNode.elm.innerText = ""
                newNode.children.forEach(child => {
                    oldNode.elm.appendChild(createElement(child))
                })
            }
        }
    } else {
        let domElm = createElement(newNode)
        if (oldNode.elm.parentNode && domElm) {
            oldNode.elm.parentNode.insertBefore(domElm, oldNode.elm)
        }
        oldNode.elm.parentNode.removeChild(oldNode.elm)
    }
    // bug: 没有处理到的情况
    newNode.elm = oldNode.elm
}